package com.tuozixuan.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.base.Preconditions;

public class AtomicIntegerDemo01 {

	public static void main(String[] args) throws InterruptedException {

		long t1 = System.currentTimeMillis();
		// 未指定初始值则默认为0
		AtomicInteger atomicInteger = new AtomicInteger();

		// 20个线程并发递增5000次
		ExecutorService executorService = Executors.newFixedThreadPool(20);
		int count = 10000;
		CountDownLatch latch = new CountDownLatch(count);
		for (int i = 0; i < count; i++) {
			executorService.execute(() -> {
				try {
					atomicInteger.incrementAndGet();
				} finally {
					latch.countDown();
				}
			});
		}
		latch.await();

		// 等所有线程结束后再获取递增后的值
		int value = atomicInteger.get();
		long t2 = System.currentTimeMillis();
		System.out.println("value:" + value + " times:" + (t2 - t1) + "ms");
		Preconditions.checkArgument(value == 10000);

		executorService.shutdown();
	}

}
